package cn.team11.smarteye.activity;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.eques.icvss.utils.ResultCode;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.badge.BadgeAnchor;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.badge.BadgePagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.badge.BadgeRule;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.team11.sds.dayi.R;
import cn.team11.smarteye.activity.callback.AlarmMessageCallback;
import cn.team11.smarteye.activity.callback.AlarmMessageResultCallback;
import cn.team11.smarteye.activity.callback.CaptureRecordCallback;
import cn.team11.smarteye.activity.callback.CaptureRecordResultCallback;
import cn.team11.smarteye.activity.callback.ConfigDeviceCallback;
import cn.team11.smarteye.activity.callback.ConfigDeviceResultCallback;
import cn.team11.smarteye.activity.callback.GuestRecordCallback;
import cn.team11.smarteye.activity.callback.GuestRecordResultCallback;
import cn.team11.smarteye.adapter.DeviceDetailPageAdatper;
import cn.team11.smarteye.base.BaseActivity;
import cn.team11.smarteye.bean.AlarmMsgInfoBean;
import cn.team11.smarteye.bean.CateyeEvent;
import cn.team11.smarteye.bean.CateyeInfoBean;
import cn.team11.smarteye.bean.RingRecordBean;
import cn.team11.smarteye.contract.DeviceDetailContract;
import cn.team11.smarteye.fragment.AlarmMessageFragment;
import cn.team11.smarteye.fragment.CaptureRecordFragment;
import cn.team11.smarteye.fragment.DetailConfigDeviceFragment;
import cn.team11.smarteye.fragment.GuestRecordFragment;
import cn.team11.smarteye.impl.DeviceDetailPresenterImpl;
import cn.team11.smarteye.misc.SConstants;
import cn.team11.smarteye.module.MyDaoManager;
import cn.team11.smarteye.utils.AppLogger;
import cn.team11.smarteye.utils.ToastUtil;
import cn.team11.smarteye.widget.CustomPagerTitleView;
import cn.team11.smarteye.widget.CustomToolbar;
import cn.team11.smarteye.widget.CustomViewPager;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Murphy on 2017/10/18.
 */

public class CateyeDeviceDetailActivity extends BaseActivity<DeviceDetailContract.Presenter> implements
        DeviceDetailContract.View, ConfigDeviceCallback, AlarmMessageCallback, GuestRecordCallback, CaptureRecordCallback, ViewPager.OnPageChangeListener {

    @BindView(R.id.detail_viewpager)
    CustomViewPager mViewPager;
    @BindView(R.id.device_detail_ctitle)
    CustomToolbar mCustomBar;
    @BindView(R.id.detail_tab_magic_indicator)
    MagicIndicator mTabIndicator;
    @BindView(R.id.network_tips_layout_01)
    View mNetTipsLayout;

    private String nick_temp = "";
    private String mBid;

    private DeviceDetailPageAdatper mDetailAdapter;

    private List<Fragment> mDetailFragments;
    private List<String> mTitle;
    private int[] mIcon = {R.drawable.icon_device_config_selector, R.drawable.icon_alert_message_selector, R.drawable.icon_guest_record_selector, R.drawable.icon_capture_record_selector};


    private DetailConfigDeviceFragment configDeviceFragment;
    private AlarmMessageFragment alarmMessageFragment;
    private GuestRecordFragment guestRecordFragment;
    private CaptureRecordFragment captureRecordFragment;

    private ConfigDeviceResultCallback mConfigResultCallback;
    private AlarmMessageResultCallback mAlarmResultCallback;
    private GuestRecordResultCallback mGuestResultCallback;
    private CaptureRecordResultCallback mCaptureResultCallback;


    private CommonNavigator commonNavigator;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_detail);
        ButterKnife.bind(this);
        init();
    }


    public void init() {

        //获取list发过来的设备bid
        mBid = getIntent().getStringExtra(SConstants.BID);
        String name = getIntent().getStringExtra(SConstants.NAME);
        new DeviceDetailPresenterImpl(this, name);
        if (mTitle == null) {
            mTitle = new ArrayList<>();
            mTitle.add(getResources().getString(R.string.config_device));
            mTitle.add(getResources().getString(R.string.alert_message));
            mTitle.add(getResources().getString(R.string.guest_record));
            mTitle.add(getResources().getString(R.string.capture_record));
        }
        Bundle b = new Bundle();
        b.putString(SConstants.NAME, name);
        mDetailFragments = new ArrayList<>();
        //初始化设备配置fragment
        configDeviceFragment = DetailConfigDeviceFragment.newInstance(b);
        mDetailFragments.add(configDeviceFragment);

        //初始化报警信息fragment
        alarmMessageFragment = AlarmMessageFragment.newInstance(b);
        mDetailFragments.add(alarmMessageFragment);


        //初始化访客记录fragment
        guestRecordFragment = GuestRecordFragment.newInstance(b);
        mDetailFragments.add(guestRecordFragment);

        //初始化抓拍记录fragment
        captureRecordFragment = CaptureRecordFragment.newInstance(b);
        mDetailFragments.add(captureRecordFragment);

        //初始化适配器
        mDetailAdapter = new DeviceDetailPageAdatper(getSupportFragmentManager(), this, mDetailFragments);
        //设置viewpager监听器
        mViewPager.setAdapter(mDetailAdapter);
        mViewPager.addOnPageChangeListener(this);
        mViewPager.setCurrentItem(0);
        mCustomBar.setMidTitle(mTitle.get(0));
        mViewPager.setScanScroll(true);


        // mTabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
        // mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));

        mCustomBar.setBackAction(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (mViewPager.getCurrentItem()) {
                    case 0:
                        finishAll();
                        break;
                    case 1:
                        if (mAlarmResultCallback != null) {
                            mAlarmResultCallback.onLeftButtonOnClick(view);
                        }
                        break;
                    case 2:
                        if (mGuestResultCallback != null) {
                            mGuestResultCallback.onLeftButtonOnClick(view);
                        }
                        break;
                    case 3:
                        if (mCaptureResultCallback != null) {
                            mCaptureResultCallback.onLeftButtonOnClick(view);
                        }
                        break;
                }
            }
        });
        mCustomBar.setRightAction(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (mViewPager.getCurrentItem()) {
                    case 1:
                        if (mAlarmResultCallback != null) {

                            mAlarmResultCallback.onRightButtonClick(view);
                        }
                        break;
                    case 2:
                        if (mGuestResultCallback != null) {
                            mGuestResultCallback.onRightButtonClick(view);
                        }
                        break;
                    case 3:
                        if (mCaptureResultCallback != null) {
                            mCaptureResultCallback.onRightButtonClick(view);
                        }
                        break;
                }
            }
        });

        //初始化tab栏
        initMagicIndicator();


    }

    private void initMagicIndicator() {
        commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mTitle == null ? 0 : mTitle.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int i) {
                final BadgePagerTitleView badgePagerTitleView = new BadgePagerTitleView(context);
                final CustomPagerTitleView simplePagerTitleView = new CustomPagerTitleView(context);
                Drawable iconDrawable = ContextCompat.getDrawable(CateyeDeviceDetailActivity.this, mIcon[i]);
                iconDrawable.setBounds(0, 0, UIUtil.dip2px(context, 20), UIUtil.dip2px(context, 20));
                simplePagerTitleView.setPadding(UIUtil.dip2px(context, 8), UIUtil.dip2px(context, 8), UIUtil.dip2px(context, 8), UIUtil.dip2px(context, 8));
                simplePagerTitleView.setClickable(true);
                simplePagerTitleView.setTextSize(12);
                simplePagerTitleView.setCompoundDrawables(null, iconDrawable, null, null);
                simplePagerTitleView.setText(mTitle.get(i));
                simplePagerTitleView.setNormalColor(ContextCompat.getColor(CateyeDeviceDetailActivity.this, R.color.color_818181));
                simplePagerTitleView.setSelectedColor(ContextCompat.getColor(CateyeDeviceDetailActivity.this, R.color.color_main_green));
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        mViewPager.setCurrentItem(i);
                        if (i != 0) mCustomBar.setMidTitle(mTitle.get(i));
                        badgePagerTitleView.setBadgeView(null);
                    }
                });
                badgePagerTitleView.setInnerPagerTitleView(simplePagerTitleView);

                badgePagerTitleView.setXBadgeRule(new BadgeRule(BadgeAnchor.CONTENT_RIGHT, -UIUtil.dip2px(context, 10)));
                badgePagerTitleView.setYBadgeRule(new BadgeRule(BadgeAnchor.TOP, UIUtil.dip2px(context, 5)));
                badgePagerTitleView.setAutoCancelBadge(true);

                return badgePagerTitleView;
            }


            @Override
            public float getTitleWeight(Context context, int index) {
                return 1.0f;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                return null;
            }
        });
        mTabIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(mTabIndicator, mViewPager);
    }

    /**
     * 添加badge
     */
    @Override
    public void addBadge(int index, int count) {
        TextView badgeTextView = (TextView) LayoutInflater.from(this).inflate(R.layout.count_badge_layout, null);
        if (count <= 0) {
            ((BadgePagerTitleView) (commonNavigator.getPagerTitleView(index))).setBadgeView(null);
        } else if (count > 99) {
            badgeTextView.setText("99+");
        } else {
            badgeTextView.setText(count + "");
        }
        ((BadgePagerTitleView) (commonNavigator.getPagerTitleView(index))).setBadgeView(badgeTextView);
    }

    @Override
    public void setCanScroll(boolean canScroll) {
        mViewPager.setScanScroll(canScroll);
    }

    @Override
    public String getNickName() {
        return StringUtils.isEmpty(nick_temp) ? getString(R.string.smart_cateye) : nick_temp;
    }

    @Override
    public void onLoginResult(boolean result) {

    }

    @Override
    public void onNetAvailable(boolean isAvailable) {
        if (isAvailable) {
            mNetTipsLayout.setVisibility(View.GONE);
        } else {
            mNetTipsLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onCateyeServiceBinded() {
        //猫眼服务已绑定
    }


    @Override
    public void setCustomTitle(String title, int index) {
        if (index == -1) {
            mCustomBar.setLeftTitle(title);
        } else if (index == 0) {
            mCustomBar.setMidTitle(title);
        } else if (index == 1) {
            mCustomBar.setRightTitle(title);
        }
    }

    @Override
    public void setCustomTitleImage(Drawable d, int index) {
        if (index == -1) {
            mCustomBar.setLeftIcon(d);
        } else if (index == 1) {
            mCustomBar.setRightIcon(d);
        }
    }

    @Override
    public void setTabVisiable(int code) {
        commonNavigator.setVisibility(code);
    }

    @Override
    public void setPresenter(DeviceDetailContract.Presenter presenter) {
        this.mBasePresenter = presenter;
    }

    @Override
    public Context getContext() {
        return getApplicationContext();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNickSetResult(CateyeEvent.SetNickEvent event) {

        if (event.getCode() != ResultCode.SUCCESS) {
            nick_temp = "";
            showToast(ToastUtil.NEGATIVE_TOAST, getString(R.string.rename_fail));
        } else {
            MyDaoManager.getInstance(this).updateNick(mBid, nick_temp);
            showToast(ToastUtil.POSITIVE_TOAST, getString(R.string.rename_success));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeleteResult(CateyeEvent.DeleteDeviceEvent event) {
        if (event.getCode() != ResultCode.SUCCESS) {
            showToast(ToastUtil.NEGATIVE_TOAST, getString(R.string.delete_fail));
        } else {
            showToast(ToastUtil.POSITIVE_TOAST, getString(R.string.delete_success));
            //退出当前界面
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRestartResult(CateyeEvent.RestartEvent event) {
        if (event.getCode() != ResultCode.SUCCESS) {
            showToast(ToastUtil.NEGATIVE_TOAST, getString(R.string.restart_fail));
        } else {
            showToast(ToastUtil.POSITIVE_TOAST, getString(R.string.restart_success));
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEnablePirResult(CateyeEvent.EnablePirEvent event) {
        if (event.getCode() != ResultCode.SUCCESS) {
            showToast(ToastUtil.NEGATIVE_TOAST, getString(R.string.enable_pid_fail));
        } else {
            //showToast(ToastUtil.POSITIVE_TOAST, getString(R.string.enable_pid_success));
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeviceInfoResult(CateyeInfoBean info) {
        if (info != null && mConfigResultCallback != null) {
            mConfigResultCallback.onDeviceDetailResult(info);
            nick_temp = info.getNick();
            if (mViewPager.getCurrentItem() == 0) mCustomBar.setMidTitle(getNickName());
        }
    }


    /**
     * 接口注册，分别注册报警消息、访客记录、抓拍记录的接口回调
     */
    public void registerConfigDeviceResultCallback(ConfigDeviceResultCallback listener) {
        this.mConfigResultCallback = listener;
    }

    public void registerAlarmMsgResultCallback(AlarmMessageResultCallback listener) {
        this.mAlarmResultCallback = listener;
    }

    public void registerGuestRecordResultCallback(GuestRecordResultCallback listener) {
        this.mGuestResultCallback = listener;
    }

    public void registerCaptureRecordResultCallback(CaptureRecordResultCallback listener) {
        this.mCaptureResultCallback = listener;
    }

    @Override
    public boolean getDeviceDetailInfo() {
        if (mBasePresenter != null) {
            return mBasePresenter.getDeviceInfo();
        } else {
            return false;
        }
    }

    @Override
    public boolean enablePirSwitch(boolean isEnable) {
        if (mBasePresenter != null) {
            mBasePresenter.enablePirSwitch(isEnable);
            return true;
        }
        return false;
    }

    @Override
    public boolean restartDevice() {
        if (mBasePresenter != null) {
            mBasePresenter.restartDevice();
            return true;
        }
        return false;
    }

    @Override
    public void startVideoCallView() {
        if (mBasePresenter != null) {
            mBasePresenter.startVideoCall();
        }
    }

    @Override
    public void deleteDevice() {
        if (mBasePresenter != null) {
            mBasePresenter.deleteDevice();
        }
    }

    @Override
    public void deviceRename(String nick) {
        if (mBasePresenter != null) {
            nick_temp = nick;
            if (mViewPager.getCurrentItem() == 0) {
                mCustomBar.setMidTitle(nick_temp);
            }
            mBasePresenter.renameDevice(nick);
        }
    }

    @Override
    public void getAlarmMsgList(long starttime, long endtime, int limit) {
        if (mBasePresenter != null) {
            mBasePresenter.getAlarmMsgList(starttime, endtime, limit);
        }
    }

    @Override
    public Observable<AlarmMsgInfoBean> getLocalAlarmMsg(final long starttime, final long endtime) {
        return Observable.create(new ObservableOnSubscribe<List<AlarmMsgInfoBean>>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<List<AlarmMsgInfoBean>> e) throws Exception {
                AppLogger.e("thread_activity" + Thread.currentThread().getName());
                List result = MyDaoManager.getInstance(CateyeDeviceDetailActivity.this).getTargetAlarmMsg(mBid, starttime, endtime);
                e.onNext(result);
                e.onComplete();
            }
        }).flatMap(new Function<List<AlarmMsgInfoBean>, ObservableSource<AlarmMsgInfoBean>>() {
            @Override
            public ObservableSource<AlarmMsgInfoBean> apply(@NonNull List<AlarmMsgInfoBean> alarmMsgInfoBeen) throws Exception {
                return Observable.fromIterable(alarmMsgInfoBeen);
            }
        }).subscribeOn(Schedulers.io());
    }

    @Override
    public void deleteAlarmMsg(String aid, int deall) {
        if (mBasePresenter != null) {
            mBasePresenter.delAlarmMsg(new String[]{aid}, deall);
        }
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        AppLogger.i("onPageSelected---"+position);
        if (position != 0) {
            mCustomBar.setRightTitle(getResources().getString(R.string.edit_txt));
            mCustomBar.setRightIcon(null);
            mCustomBar.setMidTitle(mTitle.get(position));
            if (position == 1) {
                mAlarmResultCallback.resetBadgeCount();
            } else if (position == 2) {
                mGuestResultCallback.resetBadgeCount();
            } else if (position == 3) {
                //mCaptureResultCallback.getAllSnapshots();
            }
            mCustomBar.setRightVisibility(View.VISIBLE);
        } else {
            mCustomBar.setMidTitle(getNickName());
            Drawable iconDrawable = ContextCompat.getDrawable(CateyeDeviceDetailActivity.this, R.drawable.nav_icon_back);
            iconDrawable.setBounds(0, 0, UIUtil.dip2px(CateyeDeviceDetailActivity.this, 20), UIUtil.dip2px(CateyeDeviceDetailActivity.this, 20));
            mCustomBar.setLeftIcon(iconDrawable);
            mCustomBar.setLeftTitle("");
            mCustomBar.setRightVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    @Override
    public Observable<RingRecordBean> getLocalRingList(final long starttime, final long endtime) {
        return Observable.create(new ObservableOnSubscribe<List<RingRecordBean>>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<List<RingRecordBean>> e) throws Exception {
                AppLogger.e("thread_activity" + Thread.currentThread().getName());
                List result = MyDaoManager.getInstance(CateyeDeviceDetailActivity.this).getTargetRings(mBid, starttime, endtime);
                e.onNext(result);
                e.onComplete();
            }
        }).flatMap(new Function<List<RingRecordBean>, ObservableSource<RingRecordBean>>() {
            @Override
            public ObservableSource<RingRecordBean> apply(@NonNull List<RingRecordBean> rings) throws Exception {
                return Observable.fromIterable(rings);
            }
        }).subscribeOn(Schedulers.io());
    }

    @Override
    public void getRemoteRingList(long starttime, long endtime, int limit) {
        if (mBasePresenter != null) {
            mBasePresenter.getGuestRecordList(starttime, endtime, limit);
        }
    }

    @Override
    public void deleteRings(String[] fid) {
        if (mBasePresenter !=null){
            mBasePresenter.delGuestRecord(fid, 0);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNewAlarmResult(CateyeEvent.NewAlarmEvent event) {
        if (mAlarmResultCallback != null) {
            mAlarmResultCallback.onNewAlarmMsgReceived(event.getInfo());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNewRingResult(CateyeEvent.NewRingRecordEvent event) {
        if (mGuestResultCallback != null) {
            mGuestResultCallback.onNewGuestRecordReceived(event.getRecord());
        }
    }
}

